//
//  LLSearchViewController.m
//  LLSearchView
//
//  Created by 王龙龙 on 2017/7/25.
//  Copyright © 2017年 王龙龙. All rights reserved.
//

#import "LLSearchViewController.h"
#import "LLSearchResultViewController.h"
#import "LLSearchSuggestionVC.h"
#import "LLSearchView.h"
#import "WSFSlideTitlesView.h"
#import <IQKeyboardManager.h>
#import "MDDGoodsDetailViewController.h"
#import "StoreDetailViewController.h"
//#import "EVADetailViewController.h"
//#import "AuctionDetailViewController.h"
//#import "YPAuctionDetailViewController.h"
//#import "SearchSellerPa iPinViewController.h"

@interface LLSearchViewController ()<UISearchBarDelegate ,WSFSlideTitlesViewDelegate>

@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) LLSearchView *searchView;
@property (nonatomic, strong) NSMutableArray *hotArray;
@property (nonatomic, strong) NSMutableArray *historyArray;
@property (nonatomic, strong) LLSearchSuggestionVC *searchSuggestVC;
@property (nonatomic, strong) WSFSlideTitlesView *titlesTopView;

@end

@implementation LLSearchViewController

- (NSMutableArray *)hotArray
{
    if (!_hotArray) {
        self.hotArray = [NSMutableArray arrayWithObjects:@"悦诗风吟", @"洗面奶", @"兰芝", @"面膜", @"篮球鞋", @"阿迪达斯", @"耐克", @"运动鞋", nil];
    }
    return _hotArray;
}

- (NSMutableArray *)historyArray
{
    if (!_historyArray) {
        _historyArray = [NSKeyedUnarchiver unarchiveObjectWithFile:KHistorySearchPath];
        if (!_historyArray) {
            self.historyArray = [NSMutableArray array];
        }
    }
    return _historyArray;
}
- (LLSearchView *)searchView
{
    if (!_searchView) {
        CGFloat yH = getRectNavAndStatusHight;
        if (self.searchType == 1) {
            yH += 44;
        }else{
            yH += 44;
        }
        self.searchView = [[LLSearchView alloc] initWithFrame:CGRectMake(0, yH, KScreenWidth, KScreenHeight - 64) hotArray:self.hotArray historyArray:self.historyArray];
        __weak LLSearchViewController *weakSelf = self;
        _searchView.tapAction = ^(NSString *str) {
             weakSelf.searchBar.text = str;
            weakSelf.searchSuggestVC.view.hidden = NO;
            [weakSelf.view bringSubviewToFront:weakSelf.searchSuggestVC.view];
            [weakSelf.searchSuggestVC searchTestChangeWithTest:str];
        };
    }
    return _searchView;
}


- (LLSearchSuggestionVC *)searchSuggestVC
{
    if (!_searchSuggestVC) {
        self.searchSuggestVC = [[LLSearchSuggestionVC alloc] init];
        _searchSuggestVC.view.frame = CGRectMake(0, 64, KScreenWidth, KScreenHeight - 64);
        _searchSuggestVC.view.hidden = YES;
        _searchSuggestVC.searchType = self.searchType;
        __weak LLSearchViewController *weakSelf = self;
        _searchSuggestVC.searchBlock = ^(NSString *searchTest ,NSInteger searchType) {
            if (searchType ==  1) {
                MDDGoodsDetailViewController * evc = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
                evc.goodId = searchTest;
                [weakSelf.navigationController pushViewController:evc animated:YES];
            }
            if (searchType ==  2) {
                StoreDetailViewController * evc = mGetStoryboardViewController(@"Main", @"storeDetailViewController");
                evc.storeId = searchTest;
                [weakSelf.navigationController pushViewController:evc animated:YES];
            }
            if (searchType == 3) {
                MDDGoodsDetailViewController * evc = mGetStoryboardViewController(@"Main", @"mDDGoodsDetailViewController");
                evc.goodId = searchTest;
                [weakSelf.navigationController pushViewController:evc animated:YES];
            }
//            [weakSelf pushToSearchResultWithSearchStr:searchTest];
        };
    }
    return _searchSuggestVC;
}
-(WSFSlideTitlesView *)titlesTopView{
    if (!_titlesTopView) {
        WSFSlideTitlesViewSetting *titlesSetting = [[WSFSlideTitlesViewSetting alloc] init];
        titlesSetting.titlesArr = @[ @"商品搜索",@"商店搜索"];
        titlesSetting.frame = CGRectMake(0, getRectNavAndStatusHight+1, mScreenWidth, 43);
        titlesSetting.lineHeight = 1.5;
        titlesSetting.lineHidden = NO;
        titlesSetting.spaceLineHidden = YES;
        titlesSetting.lineWidth = 50;
        titlesSetting.textColor = [UIColor AxcUI_colorWithHexCode:@"#676767"];
        titlesSetting.selectedTextColor = mContentHighlightColor;
        titlesSetting.lineBottomSpace = 0;
        titlesSetting.lineColor = mContentHighlightColor;
        titlesSetting.showRedPoint = NO;
        _titlesTopView = [[WSFSlideTitlesView alloc] initWithSetting:titlesSetting];
        _titlesTopView.delegate = self;
    }
    return _titlesTopView;
}
- (void)slideTitlesView:(WSFSlideTitlesView *)titlesView didSelectButton:(UIButton *)button atIndex:(NSUInteger)index{
    if (index == 0) {
        self.searchType = 1;
    }else if (index == 1){
        self.searchType = 2;
    }
    self.searchSuggestVC.searchType = self.searchType;
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (!_searchBar.isFirstResponder) {
        [self.searchBar becomeFirstResponder];
    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    // 回收键盘
    [self.searchBar resignFirstResponder];
//    _searchSuggestVC.view.hidden = YES;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setBarButtonItem];
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.searchType == 3) {
         self.searchSuggestVC.view.frame =  CGRectMake(0, getRectNavAndStatusHight, mScreenWidth, CGRectGetHeight(self.view.frame));
         self.searchSuggestVC.view.axcUI_Y = 0;
    }else{
         [self.view addSubview:self.titlesTopView];
         self.searchSuggestVC.view.frame =  CGRectMake(0, CGRectGetMaxY(self.titlesTopView.frame), mScreenWidth, CGRectGetHeight(self.view.frame));
         self.searchSuggestVC.view.axcUI_Y = 44;
    }
    [self.view addSubview:self.searchSuggestVC.view];
    [self addChildViewController:_searchSuggestVC];
    [self.view insertSubview:self.searchView atIndex:0];
//    [self loadHotSearch];
}
-(void)loadHotSearch
{
    /*
    NSMutableDictionary * parameters = [[NSMutableDictionary alloc]init];
   
    if (self.searchType == 1) {
         setDickeyobj(parameters, @"appraisal", @"searchHotType");
    }else{
         setDickeyobj(parameters, @"appraisal", @"auction");
    }
    [PPNetworkHelper POST:auction_search_hot parameters:parameters success:^(id responseObject) {
        if (PPSUCCESS(responseObject)) {
            NSArray * tagArr = [responseObject[@"msg"] componentsSeparatedByString:@","];
            self.hotArray = [NSMutableArray arrayWithArray:tagArr];
            
            [self.view insertSubview:self.searchView atIndex:0];
        }else{
            [AxcUI_Toast AxcUI_showCenterWithText:responseObject[@"desc"]];
        }
//        [self.contentView reloadData];
    } failure:^(NSError *error) {
//        [self.contentView.mj_header endRefreshing];
//        [self.contentView.mj_footer endRefreshing];
    } showLoading:nil];
     */
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}
- (void)setBarButtonItem
{
    [self.navigationItem setHidesBackButton:YES];
    self.hbd_barStyle = UIBarStyleBlack;
    //    self.hbd_barTintColor = [UIColor AxcUI_colorWithHexColor:@"#6933DB"];
    self.hbd_barImage = [UIImage imageNamed:@"navBackGourd."];
    self.hbd_barShadowHidden = YES;
    
    // 创建搜索框
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width, 30)];
    titleView.backgroundColor = [UIColor clearColor];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(titleView.frame) - 15, 30)];
    searchBar.placeholder = @"请输入要搜索的内容";
    searchBar.backgroundImage = mImageByName(@"clearImage");
    searchBar.tintColor = [UIColor clearColor];
    searchBar.delegate = self;
    searchBar.showsCancelButton = YES;
    searchBar.layer.masksToBounds = YES;
    searchBar.layer.cornerRadius = 15;
    searchBar.layer.borderWidth = 0.01;
    searchBar.layer.borderColor = [[UIColor clearColor] CGColor];
    UITextField *searchTextField = [searchBar valueForKey:@"_searchField"];
    searchTextField.layer.borderWidth = 0.01;
    searchTextField.layer.borderColor = [[UIColor clearColor] CGColor];
    searchTextField.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#f5f5f5"];
    searchTextField.tintColor = [UIColor AxcUI_colorWithHexCode:@"#676767"];
    [searchTextField setValue:[UIColor AxcUI_colorWithHexCode:@"#333333"] forKeyPath:@"_placeholderLabel.textColor"];
    [searchTextField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [searchBar setImage:[UIImage imageNamed:@"sort_magnifier"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UIButton *cancleBtn = [searchBar valueForKey:@"cancelButton"];
    //修改标题和标题颜色
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancleBtn.titleLabel.font = mTitleFont(14);
    [cancleBtn setTitleColor:[UIColor AxcUI_colorWithHexCode:@"#b4b4b4"] forState:UIControlStateNormal];
    
    [titleView addSubview:searchBar];
    self.searchBar = searchBar;
    [self.searchBar becomeFirstResponder];
    self.navigationItem.titleView = titleView;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}
- (void)presentVCFirstBackClick:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
/** 点击取消 */
- (void)cancelDidClick
{
    [self.searchBar resignFirstResponder];
    
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (void)pushToSearchResultWithSearchStr:(NSString *)str
{
    self.searchBar.text = str;
//    LLSearchResultViewController *searchResultVC = [[LLSearchResultViewController alloc] init];
//    searchResultVC.searchStr = str;
//    searchResultVC.hotArray = _hotArray;
//    searchResultVC.historyArray = _historyArray;
//    [self.navigationController pushViewController:searchResultVC animated:YES];
//    
    [self setHistoryArrWithStr:str];
}

- (void)setHistoryArrWithStr:(NSString *)str
{
    for (int i = 0; i < _historyArray.count; i++) {
        if ([_historyArray[i] isEqualToString:str]) {
            [_historyArray removeObjectAtIndex:i];
            break;
        }
    }
    [_historyArray insertObject:str atIndex:0];
    [NSKeyedArchiver archiveRootObject:_historyArray toFile:KHistorySearchPath];
}
#pragma mark - UISearchBarDelegate -
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self pushToSearchResultWithSearchStr:searchBar.text];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchBar.text == nil || [searchBar.text length] <= 0) {
        _searchSuggestVC.view.hidden = YES;
        [self.view bringSubviewToFront:_searchView];
    } else {
        _searchSuggestVC.view.hidden = NO;
        [self.view bringSubviewToFront:_searchSuggestVC.view];
        [_searchSuggestVC searchTestChangeWithTest:searchBar.text];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    UIImageView * bottown = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    bottown.hidden = YES;
    UIView * lineView = [[UIView alloc]initWithFrame:CGRectMake(0, getRectNavAndStatusHight, mScreenWidth, 1)];
    lineView.backgroundColor = [UIColor AxcUI_colorWithHexCode:@"#EBEBEB"];
    [self.view addSubview:lineView];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
